package com.itheima.reggie.config;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.comon.EmployeeGlobalVariable;
import com.itheima.reggie.comon.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 判断用户是否登陆
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得session
        HttpSession session = request.getSession();
        //获取session中的内容
        Employee sessionLogin = (Employee) session.getAttribute("SESSION_LOGIN");
        //判断
        if (sessionLogin != null) {
            EmployeeGlobalVariable.set(sessionLogin);
            //不为空就放行
            return true;
        } else {
            //为空就返回好东西给前端

            String Json = JSON.toJSONString(ResultInfo.error("NOTLOGIN"));
            response.getWriter().write(Json);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeGlobalVariable.remove();
    }
}
